<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchDialog"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getList"
        uniqueId="mesCoEsopInfoTable"
      >
      </ele-page>
    </div>
    <ele-form-drawer class="dialog-pack" :isLoading="isLoading" v-model="formDataDialog" v-bind="formDescDialog" :request-fn="handleSubmit" :visible.sync="visible" :title="title"> </ele-form-drawer>
    <!-- 导入弹框 -->
    <ele-form-drawer
      size="30%"
      :isLoading="isLoadingImport"
      v-model="importData"
      v-bind="importFormDescDialog"
      :request-fn="handleSubmitImport"
      :visible.sync="importVisible"
      :destroyOnClose="true"
      :title="$t('common.userImport')"
    >
      <!-- <template v-slot:file="{ desc, data, field, formData }">
              <uploadNoAuto @onchange="upLoadHandleChange" ref="uploadNoAuto"/>
          </template> -->
    </ele-form-drawer>
    <ele-form-drawer class="dialog-pack" :isLoading="isLoading" v-model="formDataDialog" v-bind="formDescDialog" :request-fn="handleSubmit" :visible.sync="visible" :title="title" size="50%">
      <template v-slot:csiModelCode>
        <el-input v-model="formDataDialog.csiModelCode" readonly :placeholder="$t('mesCoEsopInfo.placeSelectCsiModelCode')">
          <el-button slot="append" icon="el-icon-search" @click="baseGoodsDialogVisible = true"></el-button>
        </el-input>
      </template>
    </ele-form-drawer>

    <!-- 此组件放到与抽屉平级，理论上不需要修改 -->
    <ele-dialog-table
      :title="$t('mesCoEsopInfo.goodsModelTitle')"
      width="800px"
      :visible.sync="baseGoodsDialogVisible"
      :formConfig="baseGoodsSearchDialog"
      :column="baseGoodsDialogColumn"
      @getSelectData="getSelectBaseGoods"
      :getList="getBaseGoodsList"
      :hasFooter="hasBaseGoodsFooter"
    >
    </ele-dialog-table>
    <ele-dialog-table
      :title="$t('mesCoEsopInfo.toolModelTitle')"
      width="800px"
      ref="dialogFrock"
      :visible.sync="frockDialogVisible"
      :formConfig="frockSearchDialog"
      :column="frockDialogColumn"
      @getSelectData="setSelectFrock"
      :getList="getFrockList"
      :hasFooter="frockHasFooter"
    >
    </ele-dialog-table>
  </div>
</template>

<script>
import { getBaseCodeStrategy } from '@/api/common'
import { operateList, searchConfig, importFormDescDialog, formDescDialogMinxin, rowConfig } from './config'
import { getList, rowCreate, rowUpdate, rowDel, rowDetail, importData, getStationCodeList, getLineCodeList, getFrockList, coFile } from '@/api/sop/mesCoEsopInfo'
// import uploadNoAuto from "@/components/upload-no-auto";
import { baseGoodsDialog } from './mixin'
import { frockDialog } from './mixinFrock'
export default {
  name: 'mesCoEsopInfo',
  components: {
    // uploadNoAuto
  },
  mixins: [searchConfig, formDescDialogMinxin, baseGoodsDialog, frockDialog],
  data() {
    const self = this
    return {
      title: null,
      visible: false,
      isLoading: false,
      version: '',
      loading: false,
      processName: '',
      formDataDialog: {},
      getFrockList,
      // formDescDialogMinxin, //新增修改框
      // searchConfig,
      operateList,
      getList,
      isLoadingImport: false, // 导入数据loading
      importData: {}, //导入数据
      importVisible: false,
      importFormDescDialog, // 导入字段配置
      formDataDialog: {
        codeStrategy: ''
      },
      // 列表页字段的绑定配置
      column: [
        {
          type: 'selection'
        },
        {
          type: 'index',
          label: $i18n.t('common.order'),
          fixed: 'left',
          width: 60
        },
        {
          prop: 'csiSn',
          label: $i18n.t('mesCoEsopInfo.csiSn'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'csiName',
          label: $i18n.t('mesCoEsopInfo.csiName'),
          minWidth: 300,
          align: 'left',
          showOverflowTooltip: true
        },
        {
          prop: 'lineCode',
          label: $i18n.t('mesCoEsopInfo.line'),
          width: 160,
          optionProp: {
            value: 'modelingCode',
            label: 'modelingName'
          },
          option: async (data) => {
            const params = {
              modelingCode: self.$store.getters.factoryCode,
              level: 5
            }
            const list = await getLineCodeList(params)
            return list.data.result
          },
          showOverflowTooltip: true
        },
        {
          prop: 'workCellCode',
          label: $i18n.t('mesCoEsopInfo.station'),
          width: 160,
          optionProp: {
            value: 'modelingCode',
            label: 'modelingName'
          },
          option: async (data) => {
            const params = {
              modelingCode: self.$store.getters.factoryCode,
              level: 6
            }
            const list = await getStationCodeList(params)
            return list.data.result
          },
          showOverflowTooltip: true
        },
        {
          prop: 'processName',
          label: $i18n.t('mesCoEsopInfo.processName'),
          width: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'csiModelCode',
          label: $i18n.t('mesCoEsopInfo.csiModelCode'),
          width: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'csiModelName',
          label: $i18n.t('mesCoEsopInfo.csiModelName'),
          width: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'csiVersion',
          label: $i18n.t('mesCoEsopInfo.csiVersion'),
          width: 120
        },
        {
          prop: 'csiDefaultFlag',
          label: $i18n.t('mesCoEsopInfo.csiDefaultFlag'),
          width: 120,
          render: (h, { row }) => {
            return <el-switch disabled value={row.csiDefaultFlag} active-value="1" inactive-value="0"></el-switch>
          }
        },
        {
          prop: 'csiValidFlag',
          label: $i18n.t('mesCoEsopInfo.csiValidFlag'),
          width: 120,
          render: (h, { row }) => {
            return <el-switch disabled value={row.csiValidFlag} active-value="1" inactive-value="0"></el-switch>
          }
        },
        {
          prop: 'createByName',
          label: $i18n.t('common.createByName'),
          width: 120
        },
        {
          prop: 'createTime',
          label: $i18n.t('common.createTime'),
          width: 180
        },
        {
          prop: 'operate',
          label: $i18n.t('common.operation'),
          width: 160,
          fixed: 'right',
          render: (h, scope) => {
            return <ele-row-operation scope={scope} rowConfig={rowConfig} onRowOperate={this.rowOperate} />
          }
        }
      ]
    }
  },
  computed: {},
  // watch: {
  //   formDataDialog: {
  //     handler(val) {
  //       this.$set(this.formDataDialog, 'version', val.csiVersion)
  //       // this.$set(this.formDataDialog, 'lineCode', val.lineCode)
  //     },
  //     immediate: true,
  //     deep: true
  //   }
  // },
  created() {
    this.getBaseCodeStrategy()
  },
  methods: {
    //表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name
      const { codeStrategy } = this.formDataDialog
      const fnc = {
        add: () => {
          this.disableFields(false)
          this.formDataDialog = {
            csiDefaultFlag: '1',
            csiValidFlag: '1',
            codeStrategy
          }
          this.visible = true
        },
        deleteBatch: () => {
          this.$confirm(this.$t('common.deleteBatch',{name:$i18n.t('mesCoEsopInfo.name')}), this.$t('common.tip'), {
            confirmButtonText: this.$t('common.ok'),
            cancelButtonText: this.$t('common.cancel'),
            type: 'warning'
          }).then(() => {
            const ids = data.rows.map((val) => val.id).join(',')
            this.rowDel(ids)
          })
        },
        import: () => {
          this.importDialogData = {}
          this.importVisible = true
        }
      }
      fnc[data.handleName]()
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name
      const fnc = {
        edit: () => {
          this.disableFields(false)
          this.rowDetail(row.id)
          this.visible = true
        },
        detail: () => {
          this.disableFields(true)
          this.rowDetail(row.id)
          this.visible = true
        },
        delete: () => {
          this.$confirm(this.$t('common.deleteSingle',{name:$i18n.t('mesCoEsopInfo.name')}), this.$t('common.tip'), {
            confirmButtonText: this.$t('common.ok'),
            cancelButtonText: this.$t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.rowDel(row.id)
          })
        }
      }
      fnc[handleName]()
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true
      api(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || title)
          this.visible = false
          this.refresh()
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    //弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return // 判断状态
      delete data.factoryCode // 删除不需要修改的非主键字段
      delete data.remark // 删除不需要修改的非主键字段
      delete data.userDefined1 // 删除不需要修改的非主键字段
      delete data.userDefined2 // 删除不需要修改的非主键字段
      delete data.userDefined3 // 删除不需要修改的非主键字段
      delete data.userDefined4 // 删除不需要修改的非主键字段
      delete data.userDefined5 // 删除不需要修改的非主键字段
      delete data.userDefined6 // 删除不需要修改的非主键字段
      delete data.userDefined7 // 删除不需要修改的非主键字段
      delete data.userDefined8 // 删除不需要修改的非主键字段
      delete data.userDefined9 // 删除不需要修改的非主键字段
      delete data.userDefined10 // 删除不需要修改的非主键字段
      delete data.createBy // 删除不需要修改的非主键字段
      delete data.createByName // 删除不需要修改的非主键字段
      delete data.createTime // 删除不需要修改的非主键字段
      delete data.updateBy // 删除不需要修改的非主键字段
      delete data.updateByName // 删除不需要修改的非主键字段
      delete data.updateTime // 删除不需要修改的非主键字段
      delete data.activeFlag // 删除不需要修改的非主键字段
      if (data.csiFileNameEntity && data.csiFileNameEntity.length != 0) {
        data = {
          ...data,
          csiFileName: data.csiFileNameEntity[0].id,
          csiSysName: data.csiFileNameEntity[0].name
        }
      } else {
        data = { ...data, csiFileName: '', csiSysName: '' }
      }
      delete data.csiFileNameEntity
      //ywf 处理工艺流程
      if (data.csiProcessFileNameEntity && data.csiProcessFileNameEntity.length != 0) {
        data = {
          ...data,
          csiProcessFileName: data.csiProcessFileNameEntity[0].id,
          csiProcessName: data.csiProcessFileNameEntity[0].name
        }
      } else {
        data = { ...data, csiProcessFileName: '', csiProcessName: '' }
      }
      delete data.csiProcessFileNameEntity
      if (this.formDataDialog.id) {
      }
      console.log('1', data)
      const params = this.formDataDialog.id ? { title: this.$t('common.editSuccess'), api: rowUpdate, data } : { title: this.$t('common.addSuccess'), api: rowCreate, data }
      this.doSubmit(params)
    },
    //删除
    rowDel(data) {
      this.loading = true
      rowDel(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || this.$t('common.deleteSuccess'))
          this.refresh()
        })
        .finally(() => {
          this.loading = false
        })
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag
      this.formDescDialog.isShowSubmitBtn = !flag
    },
    rowDetail(id) {
      rowDetail(id).then(async (res) => {
        const data = res.data.result
        if (data.csiSysName) {
          const csiFileNameEntity = [{ name: data.csiSysName }]
          this.formDataDialog = {
            ...data,
            csiFileNameEntity: csiFileNameEntity
          }
        } else {
          this.formDataDialog = data
        }
        let keyFilter = [
          {
            code: 'csiProcessFileNameEntity',
            value: data.csiProcessFileName,
            key: 'csiProcessName'
          },
          {
            code: 'csiFileNameEntity',
            value: data.csiFileName,
            key: 'csiSysName'
          }
        ]
        await keyFilter.map(async (ite) => {
          try {
            console.log(ite.value)
            if (!ite.value) return
            let res1 = await coFile(ite.value)
            if (data[ite.key]) {
              this.$set(this.formDataDialog, ite.code, [{ name: data[ite.key], url: res1.data.result }])
              // this.formDataDialog[ite.code] = [
              //   { name: data[ite.key], url: res1.data.result },
              // ];
              // console.log(1111, this.formDataDialog);
              // data[ite.code] = [{ name: data[ite.key], url: res.data.result }];
            }
          } catch (error) {}
        })

        // this.formDataDialog.csiProcessFileNameEntity = [
        //   {
        //     name: "xcvcxv",
        //     url:
        //       "http://60.209.248.238:8182/messervice/list.png?ver…ff81a6f4de7d91c28f3ddeec8ebdbdfb256d0a33d497901f4",
        //   },
        // ];

        // debugger;
        //  this.formDataDialog = data;
        //ywf 处理工艺流程图
        // if (data.csiProcessName) {
        //   const csiProcessFileNameEntity = [{ name: data.csiProcessName }];
        //   this.formDataDialog.csiProcessFileNameEntity = csiProcessFileNameEntity;
        //   // this.formDataDialog = {
        //   //   ...data,
        //   //   csiProcessFileNameEntity: csiProcessFileNameEntity,
        //   // };
        // }

        console.log(111111111111111111, this.formDataDialog)
      })
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset)
    },
    //数据文件上传
    upLoadHandleChange(file) {
      this.$set(this.importData, 'file', file)
    },
    // 提交导入信息
    handleSubmitImport() {
      if (!this.importData.file) {
        this.$message.error(this.$t('common.uploadMsg'))
        return
      }
      const formData = new FormData()
      formData.append('file', this.importData.file.get('file'))
      this.isLoadingImport = true
      importData(formData)
        .then((res) => {
          this.$message.success(this.$t('common.importSuccess'))
          this.isLoadingImport = false
          this.importVisible = false
          this.refresh()
        })
        .catch((error) => {
          console.log('错误', error)
          this.$set(this.importData, 'file', null)
        })
        .finally(() => {
          this.isLoadingImport = false
          // this.$refs.uploadNoAuto.clearFiles()
        })
    },
    //判断是否存在编码规则
    getBaseCodeStrategy() {
      getBaseCodeStrategy({
        code: 'comSopCode',
        system: 'default',
        strategyStatus: '1'
      }).then((res) => {
        // console.log("判断是否存在编码规则", res);
        const result = res.data.result

        this.formDataDialog.codeStrategy = Array.isArray(result) && result.length > 0 ? result[0].code : ''
      })
    }
  }
}
</script>
